package com.sherwin.sourdoughapp

import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.sherwin.sourdoughapp.api.TestApi
import com.sherwin.sourdoughapp.entity.Message
import com.sherwin.sourdoughapp.socket.MySocketClient
import com.sherwin.sourdoughapp.socket.SocketApi
import com.sherwin.sourdoughapp.socket.SocketApiManager
import com.sherwin.sourdoughapp.ui.theme.SourdoughAppTheme
import com.sherwin.sourdoughapp.ui.theme.Teal200
import com.vilyever.socketclient.SocketClient
import com.vilyever.socketclient.helper.SocketClientDelegate
import com.vilyever.socketclient.helper.SocketResponsePacket
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            SourdoughAppTheme {
                MyApp()
            }
        }
        initData()
    }

    @Preview(showBackground = true, name = "Light Mode", widthDp = 320, heightDp = 480)
    @Preview(
        uiMode = Configuration.UI_MODE_NIGHT_YES,
        showBackground = true,
        name = "Dark Mode",
        widthDp = 320, heightDp = 480
    )
    @Composable
    fun PreviewMessageCard() {
        Column() {
            SourdoughAppTheme {
                Greetings()
            }
        }
    }

    @Preview(showBackground = true, name = "Light Mode", widthDp = 320, heightDp = 480)
    @Composable
    fun PreviewBoarding() {
        Column() {
            SourdoughAppTheme {
                OnBoardingScreen {

                }
            }
        }
    }

    @Composable
    private fun MyApp() {
        var shouldShowOnBoarding by rememberSaveable { mutableStateOf(true) }

        if (shouldShowOnBoarding) {
            OnBoardingScreen {
                shouldShowOnBoarding = !shouldShowOnBoarding
            }
        } else {
            Greetings(List(1000) { "$it" })
        }
    }

    @Composable
    private fun Greetings(names: List<String> = listOf("World", "Compose")) {
        LazyColumn(modifier = Modifier.padding(vertical = 4.dp)) {
            items(items = names) {
                Greeting(name = it)
            }
        }
    }
    
    @Composable
    private fun Greeting(name: String){
        Card(backgroundColor = MaterialTheme.colors.primary,
        modifier = Modifier.padding(vertical = 4.dp, horizontal = 8.dp)) {
            CardContent(name = name)
        }
    }

    @Composable
    private fun CardContent(name: String) {
        var expanded by rememberSaveable {
            mutableStateOf(false)
        }

        Row(
            modifier = Modifier
                .padding(24.dp)
                .animateContentSize(
                    animationSpec = spring(
                        dampingRatio = Spring.DampingRatioMediumBouncy,
                        stiffness = Spring.StiffnessLow
                    )
                )
        ) {
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(12.dp)
            ) {
                Text(text = "Hello, ")
                Text(
                    text = name, 
                    style = MaterialTheme.typography.h4.copy(
                        fontWeight = FontWeight.ExtraBold
                    )
                )
                if (expanded){
                    Text(text = ("Composem ipsum color sit lazy, padding theme elit, sed do bouncuy.").repeat(4))
                }
            }
            IconButton(onClick = { expanded = !expanded }) {
                Icon(imageVector =
                if (expanded) Icons.Filled.ExpandLess
                else Icons.Filled.ExpandMore,
                    contentDescription = if (expanded){
                        stringResource(id = R.string.show_less)
                    }else{
                        stringResource(id = R.string.show_more)
                    })
            }
        }
    }

    @Composable
    private fun OnBoardingScreen(func: () -> Unit) {
        var result by remember {
            mutableStateOf("空")
        }

        connectSocket()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                result = it.name
            },{
                result = it.message?:"错误"
            })

        Surface() {
            Column(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(text = "Welcome to the Basics Codelab!")
                Button(
                    modifier = Modifier.padding(vertical = 24.dp),
                    onClick = func
                ) {
                    Text(text = "Continue")
                }
                Button(
                    modifier = Modifier.padding(vertical = 24.dp),
                    onClick = {
                            SocketApiManager.connect()
                    }) {
                    Text(text = "连接socket")
                }
                Button(
                    modifier = Modifier.padding(vertical = 24.dp),
                    onClick = {
                        TestApi.sendData(data)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe {
                                result = it
                            }
                    }) {
                    Text(text = "发送数据")
                }
                Text(
                    modifier = Modifier.padding(vertical = 24.dp),
                    text = result)
            }
        }
    }

//    val data = "REPORT {\"action\":\"print\",\"name\":null,\"parameters\":{\"ProdId\":\"CYJB-001086\",\"Sequence\":\"01\"},\"ip\":\"12.1.1.22\",\"device\":\"12ergdrt6456547\",\"timestramp\":0}"
    val data = "{\"action\":\"print\",\"name\":null,\"parameters\":{\"ProdId\":\"CYJB-001086\",\"Sequence\":\"01\"},\"ip\":\"12.1.1.22\",\"device\":\"12ergdrt6456547\",\"timestramp\":0}"

    private fun connectSocket() : Observable<SocketApiManager.SocketConnect>{
        return SocketApiManager.getConnectStatusObservable()
    }

    private fun initData(){
        SocketApiManager.initSocket()
    }

    private fun send(data: ByteArray){
        MySocketClient.getInstance().localSocketClient.sendData(data)
    }

    private fun sendStr(data: String){
        val pack = MySocketClient.getInstance().localSocketClient.sendString(data)
    }

    @Composable
    fun Conversation(messages: List<Message>) {
        LazyColumn {
            items(messages) { message ->
                MessageCard(msg = message)
            }
        }
    }


    @Composable
    fun MessageCard(msg: Message) {
        Row(modifier = Modifier.padding(all = 8.dp)) {
            Image(
                painter = painterResource(id = R.drawable.icon_pig),
                contentDescription = "这是一张照片",
                modifier = Modifier
                    //设置图片大小40dp
                    .size(40.dp)
                    //剪切图片形状为圆形
                    .clip(CircleShape)
                    .border(1.5.dp, MaterialTheme.colors.secondary, CircleShape)
            )

            //添加一个水平空间在image和column之间
            Spacer(modifier = Modifier.width(8.dp))

            var isExpanded by remember { mutableStateOf(false) }
            //逐渐改变颜色
            val surfaceColor: Color by animateColorAsState(
                targetValue = if (isExpanded) MaterialTheme.colors.primary else MaterialTheme.colors.surface
            )

            Column(modifier = Modifier.clickable { isExpanded = !isExpanded }) {
                //昵称
                Text(
                    text = msg.author,
                    color = Teal200,
                    style = MaterialTheme.typography.subtitle2
                )

                //间隔
                Spacer(modifier = Modifier.height(4.dp))

                //气泡背景
                Surface(
                    shape = MaterialTheme.shapes.medium,
                    elevation = 1.dp,
                    color = surfaceColor,
                    modifier = Modifier
                        .animateContentSize()//逐渐改变大小
                        .padding(1.dp)
                ) {
                    //聊天内容
                    Text(
                        text = msg.body,
                        modifier = Modifier.padding(all = 4.dp),
                        maxLines = if (isExpanded) Int.MAX_VALUE else 1,
                        style = MaterialTheme.typography.body2
                    )
                }
            }
        }


    }


}




